<template>
  <div class="fault-monitoring">
    <div class="page-header">
      <h1>电梯故障监测</h1>
      <div class="header-actions">
        <t-date-range-picker
          v-model="dateRange"
          style="width: 300px; margin-right: 16px"
          :placeholder="['开始日期', '结束日期']"
          @change="handleDateRangeChange"
        />
        <t-select
          v-model="buildingFilter"
          style="width: 150px; margin-right: 16px"
          placeholder="选择楼栋"
          clearable
          @change="handleFilterChange"
        >
          <t-option value="" label="全部楼栋" />
          <t-option value="1号楼" label="1号楼" />
          <t-option value="2号楼" label="2号楼" />
          <t-option value="3号楼" label="3号楼" />
        </t-select>
        <t-select
          v-model="severityFilter"
          style="width: 150px; margin-right: 16px"
          placeholder="故障等级"
          clearable
          @change="handleFilterChange"
        >
          <t-option value="" label="全部等级" />
          <t-option value="严重" label="严重" />
          <t-option value="中等" label="中等" />
          <t-option value="轻微" label="轻微" />
        </t-select>
        <t-select
          v-model="statusFilter"
          style="width: 150px; margin-right: 16px"
          placeholder="处理状态"
          clearable
          @change="handleFilterChange"
        >
          <t-option value="" label="全部状态" />
          <t-option value="未处理" label="未处理" />
          <t-option value="处理中" label="处理中" />
          <t-option value="已处理" label="已处理" />
        </t-select>
        <t-input
          v-model="searchText"
          placeholder="搜索故障"
          style="width: 200px"
          clearable
        >
          <template #suffix-icon>
            <t-icon name="search" @click="onSearch" />
          </template>
        </t-input>
      </div>
    </div>

    <t-row :gutter="[16, 16]">
      <t-col :xs="24" :xl="6" v-for="stat in statistics" :key="stat.title">
        <t-card :bordered="true" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon" :style="{ backgroundColor: stat.bgColor }">
              <t-icon :name="stat.icon" size="24px" />
            </div>
            <div class="stat-info">
              <div class="stat-title">{{ stat.title }}</div>
              <div class="stat-value">{{ stat.value }}</div>
              <div class="stat-trend" :class="{ 'up': stat.trend > 0, 'down': stat.trend < 0 }">
                <t-icon :name="stat.trend > 0 ? 'arrow-up' : 'arrow-down'" size="14px" />
                <span>{{ Math.abs(stat.trend) }}%</span>
                <span class="trend-period">较上周</span>
              </div>
            </div>
          </div>
        </t-card>
      </t-col>
    </t-row>

    <t-row :gutter="[16, 16]" style="margin-top: 16px">
      <t-col :span="16">
        <t-card title="故障列表" :bordered="true">
          <template #actions>
            <t-radio-group v-model="viewType">
              <t-radio-button value="all">全部</t-radio-button>
              <t-radio-button value="today">今日</t-radio-button>
              <t-radio-button value="week">本周</t-radio-button>
              <t-radio-button value="month">本月</t-radio-button>
            </t-radio-group>
          </template>
          
          <t-table
            :columns="columns"
            :data="filteredFaults"
            :loading="loading"
            :pagination="{ pageSize: 10 }"
            bordered
            row-key="id"
            hover
          >
            <template #severity="{ row }">
              <t-tag :theme="getSeverityTheme(row.severity)" variant="light">
                {{ row.severity }}
              </t-tag>
            </template>
            <template #status="{ row }">
              <t-tag :theme="getStatusTheme(row.status)" variant="light">
                {{ row.status }}
              </t-tag>
            </template>
            <template #op="{ row }">
              <t-space>
                <t-link theme="primary" hover="color" @click="handleView(row)">查看详情</t-link>
                <t-link theme="primary" hover="color" @click="handleProcess(row)" v-if="row.status === '未处理'">处理</t-link>
                <t-link theme="success" hover="color" @click="handleComplete(row)" v-if="row.status === '处理中'">完成</t-link>
              </t-space>
            </template>
          </t-table>
        </t-card>
      </t-col>
      <t-col :span="8">
        <t-card title="故障分布" :bordered="true">
          <div class="chart-placeholder">
            <p>此处可集成图表组件展示故障分布</p>
          </div>
        </t-card>
        <t-card title="故障趋势" :bordered="true" style="margin-top: 16px">
          <div class="chart-placeholder">
            <p>此处可集成图表组件展示故障趋势</p>
          </div>
        </t-card>
      </t-col>
    </t-row>

    <!-- 故障详情对话框 -->
    <t-dialog
      v-model:visible="detailsVisible"
      header="故障详情"
      :footer="false"
      width="800px"
    >
      <div v-if="currentFault" class="fault-details">
        <t-descriptions bordered :column="2">
          <t-descriptions-item label="故障ID" :span="1">{{ currentFault.id }}</t-descriptions-item>
          <t-descriptions-item label="故障时间" :span="1">{{ currentFault.time }}</t-descriptions-item>
          <t-descriptions-item label="故障电梯" :span="1">{{ currentFault.liftName }}</t-descriptions-item>
          <t-descriptions-item label="所在楼栋" :span="1">{{ currentFault.building }}</t-descriptions-item>
          <t-descriptions-item label="故障类型" :span="1">{{ currentFault.type }}</t-descriptions-item>
          <t-descriptions-item label="故障等级" :span="1">
            <t-tag :theme="getSeverityTheme(currentFault.severity)" variant="light">
              {{ currentFault.severity }}
            </t-tag>
          </t-descriptions-item>
          <t-descriptions-item label="处理状态" :span="1">
            <t-tag :theme="getStatusTheme(currentFault.status)" variant="light">
              {{ currentFault.status }}
            </t-tag>
          </t-descriptions-item>
          <t-descriptions-item label="处理人员" :span="1">{{ currentFault.handler || '-' }}</t-descriptions-item>
          <t-descriptions-item label="故障描述" :span="2">{{ currentFault.description }}</t-descriptions-item>
          <t-descriptions-item label="处理记录" :span="2">
            <div v-if="currentFault.processRecords && currentFault.processRecords.length > 0">
              <t-timeline>
                <t-timeline-item
                  v-for="(record, index) in currentFault.processRecords"
                  :key="index"
                  :label="record.time"
                >
                  <template #dot>
                    <t-icon name="user-circle" />
                  </template>
                  <div class="record-content">
                    <div class="record-operator">{{ record.operator }}</div>
                    <div class="record-action">{{ record.action }}</div>
                  </div>
                </t-timeline-item>
              </t-timeline>
            </div>
            <t-empty v-else description="暂无处理记录" />
          </t-descriptions-item>
        </t-descriptions>
      </div>
    </t-dialog>

    <!-- 故障处理对话框 -->
    <t-dialog
      v-model:visible="processVisible"
      :header="processDialogTitle"
      :confirm-loading="confirmLoading"
      @confirm="handleProcessConfirm"
    >
      <t-form
        ref="formRef"
        :data="formState"
        :rules="rules"
        :label-width="100"
      >
        <t-form-item label="处理人员" name="handler">
          <t-input v-model="formState.handler" />
        </t-form-item>
        <t-form-item label="处理方式" name="processMethod">
          <t-select v-model="formState.processMethod">
            <t-option value="远程重启" label="远程重启" />
            <t-option value="现场维修" label="现场维修" />
            <t-option value="更换部件" label="更换部件" />
            <t-option value="其他" label="其他" />
          </t-select>
        </t-form-item>
        <t-form-item label="预计完成时间" name="estimatedTime" v-if="formState.isProcessing">
          <t-date-picker v-model="formState.estimatedTime" style="width: 100%" />
        </t-form-item>
        <t-form-item label="处理说明" name="description">
          <t-textarea v-model="formState.description" :rows="4" />
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import dayjs from 'dayjs';

// 表格列定义
const columns = [
  {
    colKey: 'id',
    title: '故障ID',
    width: '80',
  },
  {
    colKey: 'time',
    title: '故障时间',
    width: '150',
    sorter: true,
  },
  {
    colKey: 'liftName',
    title: '故障电梯',
    width: '150',
  },
  {
    colKey: 'building',
    title: '所在楼栋',
    width: '100',
  },
  {
    colKey: 'type',
    title: '故障类型',
    width: '120',
  },
  {
    colKey: 'severity',
    title: '故障等级',
    width: '100',
    cell: 'severity',
  },
  {
    colKey: 'status',
    title: '处理状态',
    width: '100',
    cell: 'status',
  },
  {
    colKey: 'op',
    title: '操作',
    width: '180',
    cell: 'op',
  },
];

// 统计数据
const statistics = [
  {
    title: '今日故障',
    value: 12,
    icon: 'error-circle',
    bgColor: '#e34d59',
    trend: 5,
  },
  {
    title: '未处理故障',
    value: 8,
    icon: 'time',
    bgColor: '#ed7b2f',
    trend: -3,
  },
  {
    title: '严重故障',
    value: 3,
    icon: 'error',
    bgColor: '#d54941',
    trend: 0,
  },
  {
    title: '故障处理率',
    value: '75%',
    icon: 'check-circle',
    bgColor: '#00a870',
    trend: 8,
  },
];

// 模拟故障数据
const faults = ref([
  {
    id: 'F001',
    time: '2023-09-18 08:15:32',
    liftName: '1号楼A电梯',
    building: '1号楼',
    type: '门控系统故障',
    severity: '严重',
    status: '已处理',
    description: '电梯门无法正常关闭，导致电梯无法运行',
    handler: '张工',
    processRecords: [
      {
        time: '2023-09-18 08:20:45',
        operator: '系统',
        action: '故障自动报警',
      },
      {
        time: '2023-09-18 08:30:12',
        operator: '张工',
        action: '接收故障通知，开始处理',
      },
      {
        time: '2023-09-18 09:45:30',
        operator: '张工',
        action: '更换门控传感器，故障已排除',
      },
    ],
  },
  {
    id: 'F002',
    time: '2023-09-18 10:22:15',
    liftName: '2号楼B电梯',
    building: '2号楼',
    type: '控制系统故障',
    severity: '中等',
    status: '处理中',
    description: '电梯控制系统出现异常，电梯无法响应呼叫',
    handler: '王工',
    processRecords: [
      {
        time: '2023-09-18 10:25:30',
        operator: '系统',
        action: '故障自动报警',
      },
      {
        time: '2023-09-18 10:40:22',
        operator: '王工',
        action: '接收故障通知，开始处理',
      },
    ],
  },
  {
    id: 'F003',
    time: '2023-09-18 11:05:48',
    liftName: '3号楼电梯',
    building: '3号楼',
    type: '电源系统故障',
    severity: '严重',
    status: '未处理',
    description: '电梯电源系统异常，电梯停止运行',
    handler: '',
    processRecords: [
      {
        time: '2023-09-18 11:06:10',
        operator: '系统',
        action: '故障自动报警',
      },
    ],
  },
  {
    id: 'F004',
    time: '2023-09-17 14:30:22',
    liftName: '1号楼B电梯',
    building: '1号楼',
    type: '限速器故障',
    severity: '严重',
    status: '已处理',
    description: '电梯限速器触发，电梯紧急停止',
    handler: '刘工',
    processRecords: [
      {
        time: '2023-09-17 14:31:05',
        operator: '系统',
        action: '故障自动报警',
      },
      {
        time: '2023-09-17 14:45:30',
        operator: '刘工',
        action: '接收故障通知，开始处理',
      },
      {
        time: '2023-09-17 16:20:15',
        operator: '刘工',
        action: '限速器调整完成，故障已排除',
      },
    ],
  },
  {
    id: 'F005',
    time: '2023-09-17 09:12:38',
    liftName: '2号楼A电梯',
    building: '2号楼',
    type: '按钮故障',
    severity: '轻微',
    status: '已处理',
    description: '电梯内部按钮失灵，无法选择楼层',
    handler: '李工',
    processRecords: [
      {
        time: '2023-09-17 09:15:22',
        operator: '系统',
        action: '故障自动报警',
      },
      {
        time: '2023-09-17 09:30:45',
        operator: '李工',
        action: '接收故障通知，开始处理',
      },
      {
        time: '2023-09-17 10:05:18',
        operator: '李工',
        action: '更换按钮面板，故障已排除',
      },
    ],
  },
  {
    id: 'F006',
    time: '2023-09-16 16:45:10',
    liftName: '1号楼A电梯',
    building: '1号楼',
    type: '显示屏故障',
    severity: '轻微',
    status: '处理中',
    description: '电梯楼层显示屏黑屏，无法显示当前楼层',
    handler: '张工',
    processRecords: [
      {
        time: '2023-09-16 16:46:30',
        operator: '系统',
        action: '故障自动报警',
      },
      {
        time: '2023-09-16 17:00:15',
        operator: '张工',
        action: '接收故障通知，开始处理',
      },
    ],
  },
  {
    id: 'F007',
    time: '2023-09-16 11:20:45',
    liftName: '2号楼B电梯',
    building: '2号楼',
    type: '噪音异常',
    severity: '中等',
    status: '已处理',
    description: '电梯运行时出现异常噪音',
    handler: '赵工',
    processRecords: [
      {
        time: '2023-09-16 11:22:10',
        operator: '系统',
        action: '故障自动报警',
      },
      {
        time: '2023-09-16 11:40:25',
        operator: '赵工',
        action: '接收故障通知，开始处理',
      },
      {
        time: '2023-09-16 13:15:40',
        operator: '赵工',
        action: '更换轴承，故障已排除',
      },
    ],
  },
  {
    id: 'F008',
    time: '2023-09-15 09:05:30',
    liftName: '3号楼电梯',
    building: '3号楼',
    type: '载重传感器故障',
    severity: '中等',
    status: '未处理',
    description: '电梯载重传感器异常，无法正确显示载重',
    handler: '',
    processRecords: [
      {
        time: '2023-09-15 09:06:15',
        operator: '系统',
        action: '故障自动报警',
      },
    ],
  },
]);

const loading = ref(false);
const dateRange = ref([]);
const buildingFilter = ref('');
const severityFilter = ref('');
const statusFilter = ref('');
const searchText = ref('');
const viewType = ref('all');
const detailsVisible = ref(false);
const currentFault = ref(null);
const processVisible = ref(false);
const processDialogTitle = ref('');
const confirmLoading = ref(false);
const formRef = ref(null);

// 表单状态
const formState = reactive({
  handler: '',
  processMethod: '',
  estimatedTime: null,
  description: '',
  isProcessing: false,
});

// 表单验证规则
const rules = {
  handler: [{ required: true, message: '请输入处理人员', trigger: 'blur' }],
  processMethod: [{ required: true, message: '请选择处理方式', trigger: 'change' }],
  description: [{ required: true, message: '请输入处理说明', trigger: 'blur' }],
};

// 根据筛选条件过滤故障
const filteredFaults = computed(() => {
  let result = [...faults.value];
  
  // 按日期范围筛选
  if (dateRange.value && dateRange.value.length === 2 && dateRange.value[0] && dateRange.value[1]) {
    const startDate = dayjs(dateRange.value[0]).startOf('day');
    const endDate = dayjs(dateRange.value[1]).endOf('day');
    result = result.filter(fault => {
      const faultDate = dayjs(fault.time);
      return faultDate.isAfter(startDate) && faultDate.isBefore(endDate);
    });
  }
  
  // 按视图类型筛选
  if (viewType.value !== 'all') {
    const today = dayjs().startOf('day');
    const weekStart = dayjs().startOf('week');
    const monthStart = dayjs().startOf('month');
    
    result = result.filter(fault => {
      const faultDate = dayjs(fault.time);
      if (viewType.value === 'today') {
        return faultDate.isAfter(today);
      } else if (viewType.value === 'week') {
        return faultDate.isAfter(weekStart);
      } else if (viewType.value === 'month') {
        return faultDate.isAfter(monthStart);
      }
      return true;
    });
  }
  
  // 按楼栋筛选
  if (buildingFilter.value) {
    result = result.filter(fault => fault.building === buildingFilter.value);
  }
  
  // 按故障等级筛选
  if (severityFilter.value) {
    result = result.filter(fault => fault.severity === severityFilter.value);
  }
  
  // 按处理状态筛选
  if (statusFilter.value) {
    result = result.filter(fault => fault.status === statusFilter.value);
  }
  
  // 按搜索文本筛选
  if (searchText.value) {
    const keyword = searchText.value.toLowerCase();
    result = result.filter(
      (fault) =>
        fault.liftName.toLowerCase().includes(keyword) ||
        fault.type.toLowerCase().includes(keyword) ||
        fault.description.toLowerCase().includes(keyword) ||
        fault.id.toLowerCase().includes(keyword)
    );
  }
  
  return result;
});

// 获取故障等级对应的主题色
const getSeverityTheme = (severity) => {
  switch (severity) {
    case '严重': return 'danger';
    case '中等': return 'warning';
    case '轻微': return 'success';
    default: return 'default';
  }
};

// 获取处理状态对应的主题色
const getStatusTheme = (status) => {
  switch (status) {
    case '未处理': return 'danger';
    case '处理中': return 'warning';
    case '已处理': return 'success';
    default: return 'default';
  }
};

// 日期范围变化处理
const handleDateRangeChange = (value) => {
  dateRange.value = value;
};

// 筛选条件变化处理
const handleFilterChange = () => {
  // 筛选逻辑已通过计算属性实现
};

// 搜索处理
const onSearch = () => {
  // 搜索逻辑已通过计算属性实现
};

// 查看故障详情
const handleView = (row) => {
  currentFault.value = { ...row };
  detailsVisible.value = true;
};

// 开始处理故障
const handleProcess = (row) => {
  currentFault.value = { ...row };
  processDialogTitle.value = '处理故障';
  formState.isProcessing = true;
  formState.handler = '';
  formState.processMethod = '';
  formState.estimatedTime = null;
  formState.description = '';
  processVisible.value = true;
};

// 完成故障处理
const handleComplete = (row) => {
  currentFault.value = { ...row };
  processDialogTitle.value = '完成故障处理';
  formState.isProcessing = false;
  formState.handler = row.handler || '';
  formState.processMethod = '';
  formState.description = '';
  processVisible.value = true;
};

// 确认处理故障
const handleProcessConfirm = () => {
  formRef.value.validate().then((result) => {
    if (result === true) {
      confirmLoading.value = true;
      
      setTimeout(() => {
        const index = faults.value.findIndex(item => item.id === currentFault.value.id);
        if (index !== -1) {
          // 更新故障记录
          if (formState.isProcessing) {
            // 开始处理
            faults.value[index].status = '处理中';
            faults.value[index].handler = formState.handler;
            
            // 添加处理记录
            if (!faults.value[index].processRecords) {
              faults.value[index].processRecords = [];
            }
            
            faults.value[index].processRecords.push({
              time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
              operator: formState.handler,
              action: `接收故障通知，开始处理：${formState.description}`,
            });
            
            MessagePlugin.success('已开始处理故障');
          } else {
            // 完成处理
            faults.value[index].status = '已处理';
            
            // 添加处理记录
            if (!faults.value[index].processRecords) {
              faults.value[index].processRecords = [];
            }
            
            faults.value[index].processRecords.push({
              time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
              operator: formState.handler,
              action: `故障处理完成：${formState.description}`,
            });
            
            MessagePlugin.success('故障已处理完成');
          }
        }
        
        processVisible.value = false;
        confirmLoading.value = false;
      }, 500);
    }
  }).catch(error => {
    console.log('验证失败:', error);
  });
};

// 生命周期钩子
onMounted(() => {
  // 这里可以添加从API获取故障列表的逻辑
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
  }, 500);
});
</script>

<style scoped>
.fault-monitoring {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.header-actions {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.stat-card {
  height: 100%;
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  margin-right: 16px;
}

.stat-info {
  flex: 1;
}

.stat-title {
  font-size: 14px;
  color: #666;
}

.stat-value {
  font-size: 24px;
  font-weight: 500;
  margin: 4px 0;
}

.stat-trend {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.stat-trend.up {
  color: #e34d59;
}

.stat-trend.down {
  color: #00a870;
}

.trend-period {
  margin-left: 4px;
  color: #999;
}

.chart-placeholder {
  height: 200px;
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
}

.fault-details {
  margin-bottom: 20px;
}

.record-content {
  margin-bottom: 8px;
}

.record-operator {
  font-weight: 500;
}

.record-action {
  color: #666;
  margin-top: 4px;
}
</style> 